package cn.yto.print.service;

import cn.yto.print.config.i18n.I18nResourceManager;
import cn.yto.print.controller.IndexController;
import cn.yto.print.enums.MessageTypeEnum;
import cn.yto.print.enums.PrintHandlerEnum;
import cn.yto.print.model.request.PrintTaskRequest;
import cn.yto.print.plugins.PrintResourceFactory;
import cn.yto.print.sqlite.domain.PrintHistoryDO;
import cn.yto.print.sqlite.service.IPrintHistoryService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

@Slf4j
@Service
public class PrintProduceService {

    @Autowired
    private IPrintHistoryService printHistoryService;
    @Autowired
    private PrintResourceFactory printResourceFactory;
    @Autowired
    private IndexController indexController;

    /**
     * 打印任务入队
     */
    public void pushPrintQueue(PrintTaskRequest printTaskRequest) {
        LinkedBlockingQueue<PrintTaskRequest> printQueue = printResourceFactory.getGlobalTaskQueue();
        printQueue.offer(printTaskRequest);
        List<PrintHistoryDO> printHistoryList = Lists.newArrayList();
        printTaskRequest.getDocuments().forEach(document -> {
            PrintHistoryDO printHistory = new PrintHistoryDO();
            printHistory.setTaskId(printTaskRequest.getTaskId());
            printHistory.setDocumentId(document.getDocumentID());
            PrintHandlerEnum expressType = PrintHandlerEnum.getPrintTypeEnum(document.getExpressPrintType());
            printHistory.setExpressType(expressType.getDesc());
            printHistory.setPrinter(StringUtils.isEmpty(document.getPrinter()) ? printTaskRequest.getPrinter() : document.getPrinter());
            printHistory.setWaybillNo(StringUtils.isBlank(document.getWaybillNo()) ? "" : document.getWaybillNo());
            printHistory.setPrintStatus(0);
            printHistoryList.add(printHistory);
        });
        printHistoryService.batchSaveHistory(printHistoryList);

        String message = String.format(I18nResourceManager.getInstance().get("index.console.printTask"), printTaskRequest.getDocuments().size());
        indexController.addConsoleLog(message, MessageTypeEnum.INFO);
    }

}
